package com.tea.room.util;

import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.tea.room.service.wechat.impl.WeChatUtil;

public class AESUtil {
    /** 
     * 密钥算法 
     */  
    private static final String ALGORITHM = "AES";  
    /** 
     * 加解密算法/工作模式/填充方式 
     */  
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding"; 
    
    
    /** 
     * AES加密 
     * 
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public static String encryptData(String data,String password) throws Exception {  
        // 创建密码器  
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        SecretKeySpec key = new SecretKeySpec(MD5.MD5Encode(password).toLowerCase().getBytes(), ALGORITHM);
        // 初始化  
        cipher.init(Cipher.ENCRYPT_MODE, key);  
        return Base64Util.encode(cipher.doFinal(data.getBytes()), "UTF-8");  
    }  
  
    /** 
     * AES解密 
     *  
     * @param base64Data 
     * @return 
     * @throws Exception 
     */  
    public static String decryptData(String base64Data,String password) throws Exception {  
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);  
        SecretKeySpec key = new SecretKeySpec(MD5.MD5Encode(password).toLowerCase().getBytes(), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);  
        byte[] decode = Base64Util.decode(base64Data, "UTF-8").getBytes();
        byte[] doFinal = cipher.doFinal(decode);
        return new String(doFinal,"utf-8");  
    }
    
    public static void main(String[] args) throws Exception {
        String xml = "<xml><return_code>SUCCESS</return_code><appid><![CDATA[wx2421b1c4370ec43b]]></appid><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[TeqClE3i0mvn3DrK]]></nonce_str><req_info><![CDATA[T87GAHG17TGAHG1TGHAHAHA1Y1CIOA9UGJH1GAHV871HAGAGQYQQPOOJMXNBCXBVNMNMAJAA]]></req_info></xml>";
        Map<String, Object> req_info = WeChatUtil.xmlToMap(xml);
        System.out.println(req_info);
        String data = AESUtil.encryptData(req_info.get("req_info").toString(), req_info.get("mch_id").toString());
        System.out.println(data);
        Map<String, Object> dataMap = WeChatUtil.xmlToMap(data);
        System.out.println(dataMap);
    }
    
}
